package com.huqing.icu.utils;

import com.huqing.icu.base.LogPlatformDto;
import com.huqing.icu.enums.DeviceTypeConstants;
import com.huqing.icu.enums.DisplayTypeConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class HeaderUtil {

    private static final Logger logger = LoggerFactory.getLogger(HeaderUtil.class);

    private static final String CLIENT_INFO = "\\s*([_a-zA-Z]*)\\s*=\\s*([\\(\\)\\.\\%\\w\\-\\,]*)\\s*";

    /**
     * 返回http头中的客户端信息
     *
     * @param request
     * @return
     */
    public static LogPlatformDto getHeaderClientInfo(HttpServletRequest request) {
        LogPlatformDto logPlatformDto = new LogPlatformDto();
        if (request == null) {
            return logPlatformDto;
        }
        String clientInfo = request.getHeader("client-info");
        if ("iOS".equals(clientInfo)) {
            //兼容之前iOS的client-info
            logPlatformDto.setOsName("ios");
            logPlatformDto.setOrigin("app");
            logPlatformDto.setAppChannel("netease");
            return logPlatformDto;
        }
        if ("android".equals(clientInfo)) {
            //兼容之前Android的client-info
            logPlatformDto.setOsName("android");
            logPlatformDto.setOrigin("app");
            logPlatformDto.setAppChannel("netease");
            return logPlatformDto;
        }
        Map<String, String> clientInfoMap = parseClientInfo(clientInfo);

        logPlatformDto.setOsName(clientInfoMap.get("os_name"));
        logPlatformDto.setOrigin(clientInfoMap.get("origin"));
        logPlatformDto.setAppChannel(clientInfoMap.get("app_channel"));
        logPlatformDto.setUdid(clientInfoMap.get("udid"));
        logPlatformDto.setMacAddr(clientInfoMap.get("mac_addr"));
        logPlatformDto.setUnisdkDeviceId(clientInfoMap.get("unisdk_deviceid"));
        logPlatformDto.setAppVersion(clientInfoMap.get("app_ver"));
        return logPlatformDto;
    }

    /**
     * 解析clientInfo的内容
     *
     * @param clientInfo
     * @return
     */
    private static Map<String, String> parseClientInfo(String clientInfo) {
        Map<String, String> map = new HashMap<>();
        if (clientInfo == null) {
            return map;
        }
        String[] infos = clientInfo.split(";");

        for (int i = 0; i < infos.length; i++) {
            String key = RegexUtil.find(CLIENT_INFO, infos[i], 1);
            String value = RegexUtil.find(CLIENT_INFO, infos[i], 2);
            try {
                if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
                    map.put(key, URLDecoder.decode(value, "UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                logger.error("url转码出错：" + value, e);
            }
        }
        return map;
    }

    /**
     * 获取当前设备系统代号，用于区分设备维度
     *
     * @param request 请求
     * @return 不是Android或iOS的返回null
     */
    public static Integer getOsCode(HttpServletRequest request) {
        LogPlatformDto logPlatformDto = getHeaderClientInfo(request);
        String osName = logPlatformDto.getOsName();
        if (StringUtils.isNotBlank(osName)) {
            if ("android".equals(osName)) {
                return DeviceTypeConstants.ANDROID.getCode();
            }
            if ("ios".equals(osName)) {
                return DeviceTypeConstants.IOS.getCode();
            }
        }

        return null;
    }

    /**
     * 获取当前的版本代号，用于区分版本维度
     *
     * @param request 请求
     * @return 不是Android或iOS的返回null
     */
    public static Integer getVersionCode(HttpServletRequest request) {
        LogPlatformDto logPlatformDto = getHeaderClientInfo(request);
        String origin = logPlatformDto.getOrigin();
        if (StringUtils.isNotBlank(origin)) {
            if ("mobileweb".equals(origin)) {
                return DisplayTypeConstants.WAP.getCode();
            }
            if ("app".equals(origin)) {
                return DisplayTypeConstants.APP.getCode();
            }
        }

        return null;
    }
}
